    export default {
        name: "home",
        setup(props) {
            const router = VueRouter.useRouter();
            const { smartSpeak } = inject('speech'); //语音
            const configs = inject('globalConfigs');
            const originalUser = ref(JSON.parse(localStorage.getItem('user')) || {});
            const user = ref({name: '',phone: '',email: '', new_password: '', old_password: ''});
            const token = ref(localStorage.getItem('token') || '');
            const dialoguser = ref(false);
            const userform = ref();
            const current = ref(1);  // 当前页
			const total = ref(0);    // 数据总量
			const pageSize = ref(6); // 每页数量
            const gjc = ref('');     // 搜索关键词
			const cxlist = ref([]);  // 列表数据
            const dialogPersonalInfo = ref(false);
            const rechargeDialogVisible = ref(false);
            const rechargePoints = ref(10) // 默认10积分起充
            const isviewvip = ref(false);

            onMounted(async() => {
                const res = await qdgetconfig();
                if(res.server?.jfsc == '开启') {
                    isviewvip.value = true;
                }
                document.title = window.APP_CONFIG.title;
                if (token.value) {
                    user.value = { ...JSON.parse(localStorage.getItem('user')) };
                    await getmyuser();
                }
                await getlist();
            });
            
            const getmyuser = async () => {
                const res = await getuser(); //从token获取用户信息
                originalUser.value = res;
                localStorage.setItem('user', JSON.stringify(res));
                user.value = {
                    username: res.Username || '',
					name: res.Name || '',
					phone: res.Phone || '',
					email: res.Email || ''
				}
            }
            
            const tologin = () => {
                router.push({name: 'login'});
            }
            
            //文章笔记
            const viewArticles = () => {
                router.push({name: 'bloglist'});
            }
            
            const isadmin = computed(() => {
                return ['admin', 'xmgly', 'tby'].includes(originalUser.value.Role);
            })
        	
        	const toadmin = async () => {
                if (isadmin) {
                    router.push({ name: 'admin' });
                }
        	}
        	
        	//签到领积分
        	const qiandao = _.debounce(async() => {
        	    const res = await addpoints();
        	    console.log(res);
        	    ElMessage.success('签到成功，获得：' + res.points_added + '积分');
        	    await getmyuser();
        	}, 300);
        	
        	//修改用户信息，debounce防抖
            const submitForm = _.debounce(async() => {
                try {
                    const valid = await userform.value.validate();
                    if (!valid) {
                        return;
                    }
                    if (!window.validators.isMobile(user.value.phone)) {
                        smartSpeak('手机号错误');
                        ElMessage.error('手机号错误');
                        return;
                    }
                    // 密码修改处理
    				if (user.value.new_password && !window.validators.isPasswordSecure(user.value.new_password)) {
    				    smartSpeak('密码必须包含大小写字母、数字和特殊字符');
                        ElMessage.error('密码必须包含大小写字母、数字和特殊字符');
                        return;
    				}
                    user.value.phone = user.value.phone.toString(); // 转换手机号为字符串
                    //提交前先校验是否有修改
                    if(user.value.name == originalUser.value.Name && user.value.phone == originalUser.value.Phone && user.value.email == originalUser.value.Email) {
                        smartSpeak('信息无变更');
                        ElMessage.error('信息无变更');
                        return;
                    }
                    let res = await updateuserapi(user.value);
                    ElMessage.success('修改成功');
                    dialoguser.value = false; // 关闭对话框
                    res = await getuser(); //从token获取用户信息
                    originalUser.value = res;
                    localStorage.setItem('user', JSON.stringify(originalUser.value));
                    user.value = {
                        username: res.Username || '',
    					name: res.Name || '',
    					phone: res.Phone || '',
    					email: res.Email || ''
    				}
                } catch (error) {
                    console.error('表单验证失败:', error);
                    smartSpeak('表单验证失败，请检查输入');
                    ElMessage.error('表单验证失败，请检查输入');
                }
            }, 300);
            
            const outLogin = () => {
                localStorage.removeItem('token');
                localStorage.removeItem('user');
                token.value = '';
                user.value = { name: '', phone: '', email: '' };
                originalUser.value = {};
                ElMessage.success("退出成功");
                smartSpeak('退出成功');
                setTimeout(() => {
                    router.push({ name: 'home' });
                }, 1000);
            }
            
            const clearCache = async () => {
                const cacheNames = await caches.keys();
                await Promise.all(cacheNames.map(cacheName => caches.delete(cacheName)));
                ElMessage.success('缓存已清理');
                setTimeout(() => {
                    router.push({ name: 'home' });
                }, 1000);
            }
            
            // 修改状态标签类型
            const getTagType = (item) => {
                const status = istime(item);
                return {
                    '查询中': 'primary',
                    '查询中，可修改': 'primary',
                    '审批流程，需登录' : 'primary',
                    '填报中': 'primary',
                    '开放': 'warning',
                    '已结束': 'danger'
                }[status.replace(/\d+/g, '').trim()] || 'info';
            };
            
			const istime = (res) => {
				if (isTimeValid(res.starttime) && isAfterShanghaiTime(res.starttime)) {
					return window.validators.formatDate(res.starttime) + '开放';
				}
				if (isTimeValid(res.endtime) && isBeforeShanghaiTime(res.endtime)) {
					return '已结束';
				}
				let title = '查询中';
				if (res.kftb?.length > 0 && res.cxtj?.length > 0) {
				    title += '，可修改';
				}else if(res.kftb?.length > 0 && res.cxtj?.length == 0){
				    title = res.processConfig?.length ? '审批流程，需登录' : '填报中';
				}
				return title;
			}
			
            // 判断今天是否已签到 LastCheckIn: "2025-04-14T21:52:46.879+08:00"
            const ischeckin = (LastCheckIn) => {
				if (!LastCheckIn) return false;
				// 配置时区选项
				const options = {
					timeZone: 'Asia/Shanghai',
					year: 'numeric',
					month: '2-digit',
					day: '2-digit'
				};
				// 解析最后签到时间并转换为上海时区日期字符串
				const lastCheckInDate = new Date(LastCheckIn);
				const lastStr = lastCheckInDate.toLocaleDateString('en-CA', options);
				// 直接获取当前时间的上海时区日期字符串
				const currentDate = new Date();
				const currentStr = currentDate.toLocaleDateString('en-CA', options);
				console.log('签到日期', lastStr);
				console.log('当前日期', currentStr);
				return lastStr === currentStr;
            }
                        
            // 分页事件处理
            const pagechange = (newPage) => {
                current.value = newPage;
                getlist();
            };
            
			const search = () => {
				current.value = 1; // 重置为第一页
				getlist();
			}

			// 清除搜索关键词
			const qc = () => {
				gjc.value = '';
				search();
			}
			
			// 获取列表数据
			const getlist = async() => {
			    const res = await index({search: gjc.value, page: current.value, pageSize: pageSize.value});
				cxlist.value = res.items; // 绑定列表数据
				total.value = res.total; // 绑定总条数
			}

            // 处理查询不存在的情况
			const handleQueryNotFound = (msg) => {
			    smartSpeak(msg);
				ElMessage.error(msg);
			}
            
            // 跳转到详情页
            //   ├── 流程表单？
            //   │    ├── 是 → 角色判断
            //   │    │    ├── 审批员 → 审批看板
            //   │    │    └── 普通用户 → 检查申请状态 → 新建/详情
            //   │    └── 否 → 执行原有逻辑
            //   └── 非流程表单 → 执行原有逻辑
            const tocx = async(item) => {
                if (!item.id) return;
                if (isTimeValid(item.starttime) && isAfterShanghaiTime(item.starttime)) {
                    return handleQueryNotFound(`查询未开始！\n 开始时间：${formatDate(item.starttime)}`)
                }
                if (isTimeValid(item.endtime) && isBeforeShanghaiTime(item.endtime)) {
                    return handleQueryNotFound(`查询已结束！\n 结束时间：${formatDate(item.endtime)}`)
                }
                if (item.cxtj.length == 0 && item.kftb?.length > 0) {
                    //判断是否流程表单
                    if(item.processConfig?.length){
                        Approval(item);
                    }else{
                        //判断是否唯一填报，如果是则要先登录查询
                        if(item.wytb) {
                            if (!token || !user.value?.name) {
                                outLogin();
                                return;
                            }
                        }else{
                            router.push({
                                name: 'formedit', 
                                params: { tableid: item.id, rowid: 0 },
                                query: { data: encodeURIComponent(JSON.stringify({})) }
                            });
                        }
                    }
                }else{
                    // 如果有关联查询条件
                    if (item.glcx) {
                        if (!token || !user.value?.name) {
                            outLogin();
                            return;
                        }
                        // 构建查询条件
                        const input = { id: item.id };
                    	if(!user.value[item.glcx]) {
                    	    smartSpeak('你的'+item.glcx+'为空');
                    		return ElMessage.error('你的'+item.glcx+'为空');
                    	}
                    	let key = item.cxtj[0];
                        input[key] = user.value[item.glcx];
                        const data = encodeURIComponent(JSON.stringify(input));
                    	if (item.dblc) {
                    		//多表联查
                    		router.push({ name: 'dblc', query: { data: data } });
                    	}else{
                    	    router.push({ name: 'cxjg', query: { data: data } });
                    	}
                    }else{
                        router.push({ name: 'cxtj', query: { id: item.id } });
                    }
                }
			}
			
			//流程表单处理
            //     ID           uint      `gorm:"primaryKey"`
            //     FormID       uint      `gorm:"index;comment:关联表单ID"`
            //     DataID       uint      `gorm:"comment:业务数据ID"`
            //     Status       string    `gorm:"size:20;default:'running';comment:状态:running/completed/rejected"`
            //     CurrentStep  int       `gorm:"default:1;comment:当前步骤"`
            //     InitiatorID  uint      `gorm:"comment:发起人ID"`
			const Approval = async (item) => {
			    const tz = () => {
			        router.push({name: 'applyDetail', params: { id: item.id }});
			    }
                await getmyuser(); //检查登录
                if(originalUser.value.Role == 'shy') {
                    tz();// 审核员跳转审批看板
                }else{
                    // 普通用户检查已有申请
                    const existingApply = await checkApply({formId: item.id});
                    if(existingApply?.process?.id) {
                        tz();// 跳转申请详情（只读）
                    } else {
                        // 新建申请
                        router.push({
                            name: 'formedit', 
                            params: { tableid: item.id, rowid: 0 },
                            query: { data: encodeURIComponent(JSON.stringify({})) }
                        });
                    }
                }
			}
			
			// 我的流程列表
			const toapplylist = () => {
			    router.push({name: 'applylist'});
			}
			
			// 积分商城
			const toproductList = () => {
			    router.push({name: 'productList'});
			}
			
			// 我的填报
			const togetmylist = () => {
			    router.push({name: 'mylist'});
			}
			
			const showRechargeDialog = () => {
                rechargePoints.value = 10;
                rechargeDialogVisible.value = true;
			}
			
			// 积分充值
			const handleRecharge = async () => {
                try {
                    // 使用你自己的 axios 实例
                    await recharge({amount: rechargePoints.value});
                    await getmyuser();
                    ElMessage.success(`成功充值 ${rechargePoints.value} 积分`)
                    rechargeDialogVisible.value = false
                } catch (error) {
                    ElMessage.error('充值失败')
                }
			}
        	
            return {
                rechargePoints,
                rechargeDialogVisible,
                showRechargeDialog,
                handleRecharge,
                isadmin,
                tologin,
                originalUser,
                user,
                token,
                toadmin,
                outLogin,
                dialoguser,
                userform,
                submitForm,
                updateuserapi,
                viewArticles,
                clearCache,
                getTagType,
                tocx,
                current,
                total,
                pageSize,
                gjc,
                pagechange,
                cxlist,
                getlist,
                search,
                qc,
                istime,
                getmyuser,
                Approval,
                qiandao,
                toapplylist,
                configs,
                toproductList, togetmylist,
                ischeckin,
                isviewvip
            };
        },
        
        template: `
<div v-if="configs.name">
	<div class="header row">
		<div class="col-lg-2 col-md-0">&nbsp;</div>
		<div class="col-lg-10 col-md-12">
			<img class="icon-logo" src="/pc_static/logo.png" />
		</div>
	</div>

	<el-dialog v-model="dialoguser" title="修改个人信息" style="padding:30px">
		<el-form :model="user" ref="userform" label-position="top">
            <el-form-item label="姓名" prop="name" :rules="[{ required: true, message: '请输入姓名' }]">
            	<el-input v-model="user.name" placeholder="输入姓名"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone" :rules="[{ required: true, message: '请输入手机号',pattern: /^1[3-9]\d{9}$/,trigger: 'blur'}]">
                <el-input v-model="user.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email":rules="[{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }]">
                <el-input v-model="user.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="当前积分">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <el-input-number v-model="originalUser.Points" :min="0" disabled style="flex: 1;"></el-input-number>
                    <el-button type="primary" @click="showRechargeDialog" style="flex-shrink: 0;">积分充值</el-button>
                </div>
            </el-form-item>
            <el-form-item label="新密码" prop="new_password">
            	<el-input type="password" v-model="user.new_password" placeholder="输入新密码"></el-input>
            	<p style="margin-top:-5px;">如果密码不需要修改，此项请留空。</p>
            </el-form-item>
            <el-form-item label="旧密码" prop="old_password">
            	<el-input type="password" v-model="user.old_password" placeholder="输入旧密码"></el-input>
            	<p style="margin-top:-5px;">修改密码必须输入旧密码。</p>
            </el-form-item>
        </el-form>
		<el-row justify="center">
			<el-col :span="8" style="text-align: center;margin: 20px;">
				<el-button type="primary" @click="submitForm">提交保存</el-button>
			</el-col>
		</el-row>
        <!-- 充值对话框 -->
        <el-dialog v-model="rechargeDialogVisible" title="积分充值" width="400px">
            <div>
                <div style="background: #f0f9eb;padding: 12px;border-radius: 4px;margin-bottom: 20px;display: flex;align-items: center;gap: 8px;color: #67c23a;">
                    <el-icon><info-filled /></el-icon>
                    <span>兑换比例：1元 = 10积分</span>
                </div>
        
                <div style="margin-bottom: 16px">
                    <div style="font-size: 14px;color: #606266;margin-bottom: 8px;">请输入充值积分</div>
                    <el-input-number v-model="rechargePoints" :min="10" :max="100000" :step="10" style="width: 100%" controls-position="right">
                        <template #append>积分</template>
                    </el-input-number>
                </div>
            
                <div style="background: #fafafa;border-radius: 4px;padding: 16px;text-align: center;">
                    <div style="font-size: 12px;color: #909399;margin-bottom: 4px;">需支付金额</div>
                    <div style="font-size: 28px;color: #e6a23c;font-weight: bold;letter-spacing: 1px;">
                        ￥{{ (rechargePoints / 10).toFixed(2) }}
                    </div>
                </div>
            </div>
            <template #footer>
                <el-button @click="rechargeDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleRecharge" style="width: 120px">立即支付</el-button>
            </template>
        </el-dialog>
	</el-dialog>

	<div class="c-center">
		<el-dropdown v-if="configs">
			<el-button type="primary" class="floating-right">
				{{token && originalUser?.Name ? originalUser.Name : '首页'}}
				<el-icon class="el-icon--right"><arrow-down /></el-icon>
			</el-button>
			<template #dropdown>
				<el-dropdown-menu>
				    <el-dropdown-item v-if="!token" @click="tologin">登录</el-dropdown-item>
				    <el-dropdown-item v-if="isadmin" @click="toadmin">进入后台</el-dropdown-item>
					<el-dropdown-item @click="viewArticles">公告文章</el-dropdown-item>
					<el-dropdown-item v-if="isviewvip" @click="toproductList()">积分商城</el-dropdown-item>
					<el-dropdown-item v-if="token" @click="togetmylist()">我的填报</el-dropdown-item>
					<el-dropdown-item v-if="token" @click="toapplylist()">我的流程</el-dropdown-item>
					<el-dropdown-item v-if="token" @click="dialoguser = true">修改信息</el-dropdown-item>
					<el-dropdown-item @click="clearCache">清理缓存</el-dropdown-item>
					<el-dropdown-item v-if="token" @click="outLogin">退出登录</el-dropdown-item>
				</el-dropdown-menu>
			</template>
		</el-dropdown>

		<div class="cen-form2">
		    <div class="ckhead">
				<div class="searchs">
				    <span>{{token && originalUser?.Name ? originalUser.Name + '，' : '首页'}}</span>&nbsp;
				    <template v-if="token && originalUser?.Name && isviewvip">
    				    <el-button type="primary" v-if="!ischeckin(originalUser.LastCheckIn)" @click="qiandao">
    				        <span style="color:#fff;">签到</span>
    				    </el-button>
    				    <span v-else>今天已签到</span>
    				    <span style="color:blue;">【积分：{{originalUser.Points}}】</span>
				    </template>
                    <el-input style="width:400px;margin-left: 40px;" v-model="gjc" placeholder="输入关键词查找项目" clearable @keyup.enter="search" @clear="qc">
                        <template #prefix>
                        	<el-icon class="el-input__icon">
                        		<search />
                        	</el-icon>
                        </template>
    					<template #append>
                            <el-button @click="search">搜索</el-button>
                        </template>
    				</el-input>
				</div>
			</div>
			<div style="padding: 20px; width: 90%; margin: auto;">
				<template v-if="total > 0">
					<div class="card-list">
						<el-card v-for="item in cxlist" :key="item.id" class="list-card" shadow="hover"	@click="tocx(item)">
							<div class="card-header">
								<div class="title" :style="{color: item.dblc ? 'red' : ''}">
									{{ item.formname }}
								</div>
								<el-tag :type="getTagType(item)" size="large" style="font-size:14px">
									{{ istime(item) }}
								</el-tag>
							</div>
							<div class="meta-info">
								<el-icon>
									<calendar />
								</el-icon>
								<span class="time-text">{{ $validators.formatDate(item.CreatedAt) }}</span>
							</div>
						</el-card>
					</div>

					<div class="pagination-container">
						<el-pagination background layout="prev, pager, next" :total="total" :current-page="current"
							:page-size="pageSize" @current-change="pagechange" :prev-text="'上一页'"
							:next-text="'下一页'" />
					</div>
				</template>

				<el-empty v-else description="暂时没有相关内容哦~">
					<template #image>
						<el-icon class="is-loading" :size="30">
							<loading />
						</el-icon>
					</template>
				</el-empty>
			</div>
		</div>
	</div>
</div>
        `
    }